<template>
  <div class="echarts" ref="chartRef">
    <ECharts :resize="true" :option="option" @click="handleChartClick" />
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import ECharts from "@/components/ECharts/index.vue";
import { ECOption } from "@/components/ECharts/config";

interface SeriesData {
  name: string;
  type: string; // 图表类型
  data: number[] | string[]; // 图表数据
  color: string[];
}

interface ChartProps {
  legendData?: string[]; // 图例
  xLabel?: (string | number)[]; // x轴数据
  data?: SeriesData[]; // y轴数据
  rotate?: number;
}

const props = withDefaults(defineProps<ChartProps>(), {
  legendData: () => ["女", "男", "总数"],
  rotate: 0,
  xLabel: () => [1, 2, 3],
  data: () => []
});

const chartRef = ref(null);
const emit = defineEmits(["barClick"]);

function processData(data) {
  let yAxisIndex = 0;
  const processedData = data.map(value => {
    // 检查是否是字符串并且包含百分号
    if (typeof value === "string" && value.includes("%")) {
      yAxisIndex = 1;
      // 去掉百分号并转换为数值
      return {
        value: parseFloat(value.replace("%", "")),
        isPercentage: true
      };
    }
    // 如果不是字符串或没有百分号，则保持原值
    return {
      value: value,
      isPercentage: false
    };
  });
  return [processedData, yAxisIndex];
}

// 将 data 转换为 series 的方法
function generateSeries(data: SeriesData[]): any[] {
  const seriesArray: any[] = [];

  data.forEach(item => {
    const [processedData, yAxisIndex] = processData(item.data);

    const commonLabel = {
      show: true,
      fontSize: 18,
      formatter: (params: any) => {
        const dataItem = processedData[params.dataIndex];
        return dataItem.isPercentage ? `${dataItem.value}%` : dataItem.value;
      }
    };

    switch (item.type) {
      case "bar":
        seriesArray.push({
          name: item.name,
          type: item.type,
          yAxisIndex: yAxisIndex,
          stack: "总量",
          barMaxWidth: 35,
          barGap: "10%",
          itemStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 1,
              colorStops: [
                { offset: 0, color: item.color[0] }, // 起始颜色
                { offset: 1, color: item.color[1] } // 结束颜色
              ],
              global: false // 如果需要全局渐变，将其设为 true
            }
          },
          label: {
            ...commonLabel,
            position: "inside"
          },
          data: processedData.map(item => item.value)
        });
        break;
      case "line":
        // 处理线图数据
        seriesArray.push({
          name: item.name,
          type: item.type,
          yAxisIndex: yAxisIndex,
          symbolSize: 10,
          symbol: "circle",
          itemStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 1,
              colorStops: [
                { offset: 0, color: item.color[0] }, // 深蓝色
                { offset: 1, color: item.color[1] } // 浅蓝色
              ],
              global: false // 如果需要全局渐变，将其设为 true
            }
          },
          label: {
            ...commonLabel,
            position: "top",
            fontFamily: "futura",
            color: "#fff"
          },
          data: processedData.map(item => item.value)
        });
        break;
      default:
        throw new Error(`Unsupported type: ${item.type}`);
    }
  });

  // 返回包含所有 series 数据的数组
  return seriesArray;
}

const option: ECOption = {
  // backgroundColor: "#007aff",
  tooltip: {
    trigger: "axis",
    appendToBody: true,
    backgroundColor: "rgba(31,35,39,0)",
    borderColor: "rgba(31,35,39,0)",
    extraCssText:
      "text-align:left;background-image: linear-gradient(180deg, #306698 0%, rgba(23,64,100,0.16) 100%);border- radius: 4px; border:1px solid rgba(255,255,255,0);backdrop-filter: blur(5px);",
    textStyle: {
      color: "#fff"
    },
    formatter: (params: any) => {
      let result = `${params[0].axisValue}<br/>`;
      params.forEach(param => {
        const isPercentage = param.componentIndex === 1 || (typeof param.data === "object" && param.data.isPercentage);
        const value = isPercentage ? `${param.value}%` : param.value;
        result += `${param.marker} ${param.seriesName}: ${value}<br/>`;
      });
      return result;
    },
    axisPointer: {
      type: "shadow",
      shadowStyle: {
        color: {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: "rgba(76,110,218,0.08)" // 0% 处的颜色
            },
            {
              offset: 1,
              color: "rgba(75,85,117,0)" // 100% 处的颜色
            }
          ],
          global: false // 缺省为 false
        }
      }
    }
  },
  grid: {
    borderWidth: 0,
    top: 50,
    bottom: 50,
    left: 20,
    right: 20
  },
  legend: {
    x: "4%",
    top: "3%",
    textStyle: {
      color: "#90979c",
      fontSize: 15
    },
    data: props.legendData
  },
  calculable: true,
  xAxis: [
    {
      type: "category",
      axisLine: {
        lineStyle: {
          color: "#ffffff"
        }
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitArea: {
        show: false
      },
      axisLabel: {
        interval: 0,
        rotate: props.rotate, // 旋转角度，单位是度
        fontSize: 16,
        formatter: function (value) {
          let result = "";
          for (let i = 0; i < value.length; i += 3) {
            result += value.substring(i, i + 3) + "\n";
          }
          return result.trim(); // 去除末尾可能多余的换行符
        }
      },
      data: props.xLabel
    }
  ],
  yAxis: [
    {
      type: "value",
      splitLine: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: "#ffffff"
        }
      },
      axisTick: {
        show: false
      },
      splitArea: {
        show: false
      },
      axisLabel: {
        show: false
      }
    },
    {
      type: "value",
      splitLine: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: "#ffffff"
        }
      },
      axisTick: {
        show: false
      },
      splitArea: {
        show: false
      },
      axisLabel: {
        show: false,
        formatter: value => `${value.toFixed(0)}%` // 百分比格式
      }
    }
  ],
  series: generateSeries(props.data)
};

// 添加点击事件处理
const handleChartClick = (params: any) => {
  // console.log("点击了图表：", params);
  emit("barClick", params);
};
</script>

<style scoped lang="scss">
.echarts {
  width: 100%;
  height: 100%;
  color: rgb(31 19 202);
  background-image: radial-gradient(
    circle at 50% 0%,
    rgb(23 173 255 / 20%) 0%,
    rgb(23 173 255 / 20%) 0%,
    rgb(40 115 255 / 6%) 99%
  );
}
</style>
